<?php


namespace app\index\model;


use app\index\controller\PaypalApi;
use think\Model;

class OrderPayment extends Model
{
    /**
     * @var string[]
     */
    public static $pay_way_list=['BANK_TRANSFER','CASH','CHECK','CREDIT_CARD','DEBIT_CARD','PAYPAL','WIRE_TRANSFER','OTHER'];

    /**
     * recordPayment
     * 添加付款信息
     * @url
     * @method
     * @param $data
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @author Asira
     * @date 2021/1/12
     */
    public static function recordPayment($data): array
    {
        $OrderPaymentClass=new self();
        $OrderClass=new Order();
        $OrderHistoryClass=new OrderHistory();

        $order_data=$OrderClass::getPaymentById($data['order_id']);

        if(empty($order_data)){
            return ['status'=>false,'result'=>'未找到符合的账单'];
        }

        if(round($data['amount'],2)>=round($order_data['total_price']-$order_data['amount_paid']-$data['amount_discount'],2)){
            $update_order['pay_type']=4;
        }else{
            $update_order['pay_type']=3;
        }
        $update_order['amount_paid']=round($order_data['amount_paid']+$data['amount'],2);
        $update_order['payment_time']=$data['payment_date'];
        $update_order['amount_discount']=$data['amount_discount'];

        $OrderPaymentClass->startTrans();
        try {
            $result=$OrderClass->isUpdate()->save($update_order, ['id' => $data['order_id']]);
            if($result===false){
                return ['status'=>false,'result'=>'更新账单状态失败'];
            }

            $result=$OrderHistoryClass->isUpdate(false)->save(['order_id'=>$data['order_id'],'operator'=>$data['create_user'],'operational'=>'添加付款. '.$data['amount'].'USD']);
            if($result===false){
                return ['status'=>false,'result'=>'添加历史失败'];
            }
            $order=Order::getOrderById($data['order_id']);
            $items=OrderItem::getOrderItemsById($data['order_id']);
            $order['items']=$items;

            ['status'=>$status,'result'=>$result]=PaypalApi::updateInvoice($order);
            if($status===false){
                return ['status'=>false,'result'=>$result];
            }
            ['status'=>$status,'result'=>$result]=PaypalApi::recordPayment($order_data['receipt_number'],$order_data['create_group'],$data);
            if($status===false){
                return ['status'=>false,'result'=>$result];
            }
            $order_payment_data=[
                'order_id'=>$data['order_id'],
                'payment_id'=>$result['payment_id'],
                'invoice_payment_id'=>$data['invoice_payment_id'],
                'payment_date'=>date('Y-m-d H:i:s'),
                'method'=>$data['method'],
                'amount'=>$data['amount'],
                'note'=>$data['note'],
                'create_user'=>$data['create_user'],
            ];
            $result=$OrderPaymentClass->isUpdate(false)->save($order_payment_data);
            if($result===false){
                return ['status'=>false,'result'=>'增加付款信息失败'];
            }
            $OrderPaymentClass->commit();
            return ['status'=>true,'result'=>['msg'=>'更新成功','pay_type'=>$update_order['pay_type']]];
        }catch (\Exception $e){
            $OrderPaymentClass->rollback();
            trace('更新付款失败'.$e->getMessage(),'error');
            return ['status'=>false,'result'=>'更新付款失败'];
        }
    }
    public static function recordPaymentByCardId($data,$customer_id):array
    {
        $OrderPaymentClass=new self();
        $OrderClass=new Order();
        $OrderHistoryClass=new OrderHistory();
        $MemberClass=new Member();
        //判断是否是自己的会员卡
        $res=$MemberClass->where(['customer_id'=>$customer_id,'id'=>$data['member_id'],'del_flag'=>0])->find();
        if (!$res){
            return ['status'=>false,'result'=>'会员卡错误'];
        }
        if($data['amount']>$res['balance']){
            return ['status'=>false,'result'=>'会员卡余额不足'];
        }
        $where['id']=['=',$data['order_id']];
        $where['order_status']=['=',1];
        $where['del_flag']=['=',0];
        $where['pay_type']=['=',2];
        $order_data=$OrderClass->where($where)
            ->field('id,receipt_number,items_price,ship_fee,total_price,pay_type,payment_type,partial_pay,amount_discount,amount_paid,tip_paid,create_group,customer_id')
            ->find();
        if(empty($order_data)){
            return ['status'=>false,'result'=>'未找到符合的账单'];
        }
        $update_order['amount_paid']=round($data['amount'],2);
        $update_order['payment_time']=$data['payment_date'];
        $update_order['amount_discount']=$data['amount_discount'];
        $update_order['member_pay_type']=1;
        $update_order['pay_type']=4;
        $OrderPaymentClass->startTrans();
        try {
            $result = $OrderClass->isUpdate()->save($update_order, ['id' => $data['order_id']]);
            if ($result === false) {
                return ['status' => false, 'result' => '更新账单状态失败'];
            }
            $result=$OrderHistoryClass->isUpdate(false)->save(['order_id'=>$data['order_id'],'operator'=>$data['create_user'],'operational'=>'添加付款. '.$data['amount'].'USD']);
            if($result===false){
                return ['status'=>false,'result'=>'添加历史失败'];
            }
            $order=Order::getOrderById($data['order_id']);
            $items=OrderItem::getOrderItemsById($data['order_id']);
            $order['items']=$items;

            ['status'=>$status,'result'=>$result]=PaypalApi::updateInvoice($order);
            if($status===false){
                return ['status'=>false,'result'=>$result];
            }
            ['status'=>$status,'result'=>$result]=PaypalApi::recordPayment($order_data['receipt_number'],$order_data['create_group'],$data);
            if($status===false){
                return ['status'=>false,'result'=>$result];
            }

            $member_update['balance']=round($res['balance']-$data['amount'],2);
            $result=$MemberClass->where(['id'=>$data['member_id']])->update($member_update);
            if (!$result){
                return ['status'=>false,'result'=>'扣款失败'];
            }
            $history_data=['customer_id'=>$customer_id,'member_id'=>$data['member_id'],'order_id'=>$data['order_id'],'balance'=>$data['amount']];
            ['status'=>$status,'result'=>$result]=MemberCostHistory::add($history_data);
            if ($status==false){
                return ['status'=>false,'result'=>$result];
            }
            $OrderPaymentClass->commit();
            return ['status'=>true,'result'=>['msg'=>'更新成功','pay_type'=>$update_order['pay_type']]];

        }catch (\Exception $e){
            $OrderPaymentClass->rollback();
            trace('更新付款失败'.$e->getMessage(),'error');
            return ['status'=>false,'result'=>'更新付款失败'];
        }

    }

    public static function getHomePaymentList($search_group,$search_user){
        $OrderPaymentClass=new self();

        $where['o.pay_type']=['in',[3,4]];
        $where['o.del_flag']=['=',0];
        $where['o.logistics_status']=['in',[0,1]];
        if($search_group) {
            $where['o.create_group'] = ['=', $search_group];
        }
        if($search_user) {
            $where['o.create_user'] = ['in', $search_user];
        }

        $order=$OrderPaymentClass->alias('op')
            ->join('order o','op.order_id=o.id','left')
            ->join('customer c','o.customer_id=c.id','left')
            ->where($where)
            ->field('o.order_id,o.total_price,o.amount_paid,op.amount,c.nick_name,DATE_FORMAT(op.payment_date,\'%Y-%m-%d\') payment_date,o.customer_id')
            ->order('op.payment_date','desc')
            ->limit(0,100)->select()->toArray();
        foreach ($order as $key=>$value){
            if($value['amount_paid']>=500){
                $order[$key]['ship_status']=true;
            }else{
                $order[$key]['ship_status']=false;
            }
            $order[$key]['is_new']=false;
        }
        return $order;
    }
}